using LF.Application.Services.interfaces;
using LF.Domain.Entities;
using LF.Domain.Services;
using LF.Shared.Dtos.Out;
using LF.Shared.Dtos.Input;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Uow;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Volo.Abp.Users;
using LF.Application.Extend;

namespace LF.Application.Services.Iml
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Sys)]
    public class MenuService : BaseService, IMenuService
    {
        private readonly IMenuManagerService _manager;
        private readonly IHttpContextAccessor _httpContext;

        public MenuService(
            IMenuManagerService manager,
            IObjectMapper<LFModule> mapper,
            IGlobalManagerService globalManager,
            IHttpContextAccessor httpContext) : base(mapper, globalManager)
        {
            _manager = manager;
            _httpContext = httpContext;
        }

        [LFAuthorize("菜单列表", "system:menu:list")]
        public Result<List<MenuOut>> List()
        {
            var menus = _manager.GetMenuTree();
            var result = _mapper.Map<List<Menu>, List<MenuOut>>(menus);
            return Ok(result);
        }

        /// <summary>
        /// 获取菜单权限编码
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>菜单权限编码列表</returns>
        [HttpGet("permissions/{userId}")]
        public Result<List<string>> GetPermissionCodes(Guid userId)
        {
            var permissionCodes = _manager.GetPermissionCodes(userId);
            return Ok(permissionCodes);
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <returns>权限列表</returns>
        public Result<List<string>> GetPermissionsList()
        {
            var permissions = _globalManager.ToList<Permission>(p=>!p.IsDelete)?.Select(p=>p.Code).ToList();
            return Ok(permissions);
        }

        /// <summary>
        /// 获取当前用户的权限编码列表
        /// </summary>
        /// <returns>权限编码列表</returns>
        [HttpGet("current-permissions")]
        public Result<List<string>> GetCurrentUserPermissions()
        {
            var userId = _httpContext.HttpContext.User.GetUserId();
            if (!userId.HasValue)
            {
                return Error<List<string>>("未登录");
            }

            var permissionCodes = _manager.GetPermissionCodes(userId.Value);
            return Ok(permissionCodes);
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        [LFAuthorize("菜单分页列表", "system:menu:page")]
        public Result<MenuSearchOut> Menus([FromQuery] MenuSearch search)
        {
            var list = _manager.All(search.Index, search.PageSize, search.Key);
            var items = _mapper.Map<List<Menu>, List<MenuOut>>(list);
            var count = _manager.Count(search.Key);
            return Ok(new MenuSearchOut { Items = items, TotalCount = count });
        }

        /// <summary>
        /// 获取菜单详情
        /// </summary>
        [LFAuthorize("菜单详情", "system:menu:read")]
        public Result<MenuOut> Get(Guid id)
        {
            // 从数据库获取菜单项
            var menu = _globalManager.Get<Menu>(id);
            if (menu == null)
            {
                return Error<MenuOut>("菜单不存在");
            }

            var result = _mapper.Map<Menu, MenuOut>(menu);
            return Ok(result);
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        [LFAuthorize("创建菜单", "system:menu:create")]
        public Result Create(MenuOut menuDto)
        {
            // 防止重复的菜单编码
            if (!string.IsNullOrEmpty(menuDto.Code) && 
                _manager.CheckMenuCodeExists(menuDto.Code))
            {
                return Error("菜单编码已存在");
            }

            // 如果未提供编码，自动生成
            if (string.IsNullOrEmpty(menuDto.Code))
            {
                menuDto.Code = _manager.GenerateMenuCode(menuDto.ParentId);
            }

            var menu = _mapper.Map<MenuOut, Menu>(menuDto);
            menu.Id = Guid.NewGuid();
            
            _globalManager.Insert(menu);
            return Ok();
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        [LFAuthorize("更新菜单", "system:menu:update")]
        public Result Update(Guid id, MenuOut menuDto)
        {
            // 获取要更新的菜单
            var menu = _globalManager.Get<Menu>(id);
            if (menu == null)
            {
                return Error("菜单不存在");
            }

            // 防止重复的菜单编码
            if (!string.IsNullOrEmpty(menuDto.Code) && 
                menu.Code != menuDto.Code && 
                _manager.CheckMenuCodeExists(menuDto.Code, id))
            {
                return Error("菜单编码已存在");
            }

            // 更新菜单
            _mapper.Map(menuDto, menu);
            menu.Id = id;
            
            _globalManager.Update(menu);
            return Ok();
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        [LFAuthorize("删除菜单", "system:menu:delete")]
        public Result Delete(Guid id)
        {
            // 检查是否有子菜单
            var children = _globalManager.ToList<Menu>(m => m.ParentId == id && !m.IsDelete);
            if (children.Any())
            {
                return Error("请先删除子菜单");
            }

            // 逻辑删除菜单
            var success = _globalManager.Delete<Menu>(id);
            if (!success)
            {
                return Error("删除失败");
            }

            return Ok();
        }
    }
} 